<template>
  <a-modal
      v-model:visible="visible"
      :title="title"
      @ok="handleOk"
      :loading="loading"
  >
    <a-form
        ref="formRef"
        :model="formData"
        v-bind="{labelCol: { span: 8 },wrapperCol: { span: 16 }}"
    >
      <a-form-item name="username" label="账号" :rules="[{ required: true, message: '请填写账号!' }]">
        <a-input v-model:value="formData.username"/>
      </a-form-item>
      <a-form-item name="password" label="密码" :rules="formData.id?[]:[{ required: true, message: '请输入密码!' }]">
        <a-input-password v-model:value="formData.password" placeholder="请输入密码"/>
      </a-form-item>
      <a-form-item name="nickName" label="昵称">
        <a-input v-model:value="formData.nickName"/>
      </a-form-item>
      <a-form-item name="sex" label="性别">
        <v-select-dict-item code="sex" v-model="formData.sex"/>
      </a-form-item>
      <a-form-item name="orgId" label="机构">
        <v-select-org code="orgId" v-model="formData.orgId"/>
      </a-form-item>
      <a-form-item name="roleIds" label="角色">
        <v-select-role v-model:role-ids="formData.roleIds"/>
      </a-form-item>
      <a-form-item name="status" label="状态" :rules="[{ required: true, message: '请选择状态!' }]">
        <v-radio-dict-item code="USER_STATUS" v-model="formData.status"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { Ref, ref } from 'vue'
import { FormInstance, message } from 'ant-design-vue'
import { saveUser } from '@/api/sys-user'
import VSelectDictItem from '@/components/VSelectDictItem.vue'
import VRadioDictItem from '@/components/VRadioDictItem.vue'
import { useModalForm } from '@/modules/use-modules'
import VSelectOrg from '@/components/VSelectOrg.vue'
import VSelectRole from '@/components/VSelectRole.vue'

const formRef = ref<FormInstance>() as Ref<FormInstance>

const {
  formData,
  loading,
  visible,
  title,
  open,
  close
} = useModalForm({ status: '1' }, async (data: any) => {
  return {
    ...data,
    password: ''
  }
})

const emits = defineEmits(['ok'])

const handleOk = async () => {
  await formRef.value.validate()
  await saveUser(formData.value)
  message.success('操作成功')
  emits('ok')
  close()
}

defineExpose({ open })
</script>
